package deviceauthlogic

import (
	"context"
	"gitee.com/unitedrhino/protocol-wumei/service/pwumeisvr/internal/domain"
	"gitee.com/unitedrhino/share/ctxs"
	"gitee.com/unitedrhino/share/errors"
	"gitee.com/unitedrhino/things/share/devices"
	"strings"

	"gitee.com/unitedrhino/protocol-wumei/service/pwumeisvr/internal/svc"
	"gitee.com/unitedrhino/protocol-wumei/service/pwumeisvr/pb/pwumei"

	"github.com/zeromicro/go-zero/core/logx"
)

type AccessAuthLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAccessAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AccessAuthLogic {
	ctx = ctxs.WithRoot(ctx)
	return &AccessAuthLogic{
		ctx:    ctxs.WithRoot(ctx),
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

var (
	AccessMap = map[string]string{
		devices.Pub: "post",
		devices.Sub: "get",
	}
)

// 设备操作认证
func (l *AccessAuthLogic) AccessAuth(in *pwumei.AccessAuthReq) (*pwumei.Response, error) {
	ci, err := domain.ParseClientID(in.ClientID)
	if err != nil {
		return nil, err
	}
	topics := strings.Split(in.Topic, "/")
	if topics[0] == "" {
		topics = topics[1:]
	}
	if len(topics) != 4 {
		return nil, errors.Permissions
	}
	if topics[0] != ci.ID || topics[1] != ci.DeviceName || topics[3] != AccessMap[in.Access] {
		return nil, errors.Permissions
	}
	return &pwumei.Response{}, nil
}
